<script setup lang="ts">
import { ref } from "vue";
import { getDataBySQLDesc } from "@/api/common";
import { onMounted, onBeforeUnmount } from "vue";
import dayjs from "dayjs";
import EChartsComponent from "@/components/EChartsComponent/index.vue";
import { usePieChartOption, useBarChartOption } from "./chartOptions";

// 常量定义
const title = "待 物 流 发 货";
const decorationColors = ["#568aea", "#000000"];
const REFRESH_INTERVAL = 10 * 60 * 1000; // 10分钟刷新一次

// 表格配置
const config = ref({
  header: ["订单号", "跟单", "物流/快递", "灯具/模组数量", "备货数量"],
  data: [],
  headerHeight: 50,
  index: false,
  columnWidth: [200, 80, 200, 180, 80],
  align: "center",
  headerBGC: "#0f1325", // 表头
  oddRowBGC: "#0f1325", // 奇数行
  evenRowBGC: "#171c33", // 偶数行
  rowNum: 10
});

// 数字展示配置
const createDigitalFlopConfig = () => ({
  number: [0],
  toFixed: 0,
  textAlign: "center",
  content: "{nt}",
  style: {
    fontSize: 26
  }
});

const config1 = ref(createDigitalFlopConfig());
const config2 = ref(createDigitalFlopConfig());

// 图表配置
const { option } = usePieChartOption();
const { option2 } = useBarChartOption();

// 数据状态
const data3 = ref({
  time: "",
  NotBatch: "",
  AllBatch: ""
});
const currentTime = ref("");

// 定时器管理
let refreshInterval: number | null = null;
let intervalId: number | null = null;
let serverTime: dayjs.Dayjs | null = null;
let localTimestamp = 0;

// 获取服务器时间
const getTimeNow = async (): Promise<void> => {
  const params = { action: "public/get_server_sysdate" };
  const { data } = await getDataBySQLDesc(params);
  const dateStr = data[0].日期时间;

  localTimestamp = Date.now();
  serverTime = dayjs(dateStr, "YYYY-MM-DD HH:mm:ss");
};

// 开始计时器
const startTimer = (): void => {
  if (intervalId) clearInterval(intervalId);

  const update = (): void => {
    if (!serverTime) return;

    const elapsed = Date.now() - localTimestamp;
    const currentServerTime = serverTime.add(elapsed, "millisecond");
    currentTime.value = currentServerTime.format("YYYY-MM-DD dddd HH:mm:ss");
  };

  update(); // 立即执行一次
  intervalId = window.setInterval(update, 1000);
};

// 清除计时器
onBeforeUnmount(() => {
  if (refreshInterval) {
    clearInterval(refreshInterval);
    refreshInterval = null;
  }
  if (intervalId) {
    clearInterval(intervalId);
    intervalId = null;
  }
});

// 获取表格数据
const getTableData = async (params: any): Promise<void> => {
  const { data } = await getDataBySQLDesc(params);

  const fieldsToExtract = [
    "订单单号",
    "跟单",
    "出通物流",
    "申请出通数量",
    "备货数量"
  ];

  config.value.data = data.map(item =>
    fieldsToExtract.map(field => item[field] || "")
  );
};

// 获取饼图数据
const getChartsData3 = async (params: any): Promise<void> => {
  const { data } = await getDataBySQLDesc(params);

  data3.value.time = dayjs(data[0].日期).format("YYYY-MM-DD") || "";
  data3.value.NotBatch = data[0].今日已发 || 0;
  data3.value.AllBatch = data[0].今日应发 || 0;

  const newNumber = Number(data[0]?.今日已发) || 0;
  const newNumber1 = Number(data[0]?.今日应发) || 0;

  config1.value.number = [newNumber];
  config2.value.number = [newNumber1];

  const num = Number(data[0].发货率) * 100 || 0;
  option.value.title.text = "{a|发货率}\n{b| " + num + " %}";
  option.value.series[0].data = [num];
};

// 获取柱状图数据
const getChartsData2 = async (params: any): Promise<void> => {
  const { data } = await getDataBySQLDesc(params);

  option2.value.series[0].data = [];
  option2.value.xAxis[0].data = [];

  data.forEach(item => {
    option2.value.series[0].data.push({
      name: item.发货日期,
      value: item.发货批次
    });
    const formattedDate = dayjs(item.发货日期).format("YYYY-MM-DD");
    option2.value.xAxis[0].data.push(formattedDate);
  });
};

// 获取参数的通用函数
const fetchParams = async (hsmc: string): Promise<Record<string, string[]>> => {
  const params = { action: "public/get_bi_sjfw", hsmc };
  const { data } = await getDataBySQLDesc(params);

  return data.reduce((acc, item) => {
    acc[item["参数编码"]] = item["参数值"];
    return acc;
  }, {});
};

// 自动刷新数据
const startAutoRefresh = (): void => {
  if (refreshInterval) clearInterval(refreshInterval);

  const fetchAllData = async (): Promise<void> => {
    // 获取参数并加载数据
    const [result, result1, result2, result3] = await Promise.all([
      //下面2个是滚屏参数
      fetchParams("get_ckfhkb_jrwfhmx"),
      fetchParams("get_ckfhkb_jrwfhmx_bhmx"),
      //块状图参数and饼图
      fetchParams("get_ckfhkb_jrfhfx"),

      //柱状图参数
      fetchParams("get_ckfhkb_mrfhfx")
    ]);

    // 加载滚屏数据
    const params = {
      action: "biz/reports/get_ckfhkb_jrwfhmx_bhmx",
      ...result,
      ...result1
    };
    getTableData(params);

    // 加载饼图数据
    const params1 = {
      action: "biz/reports/get_ckfhkb_jrfhfx",
      ...result2
    };
    getChartsData3(params1);

    // 加载柱状图数据
    const params2 = {
      action: "biz/reports/get_ckfhkb_mrfhfx",
      ...result3
    };
    getChartsData2(params2);
  };

  // 立即执行一次
  fetchAllData();

  // 设置定时刷新
  refreshInterval = window.setInterval(fetchAllData, REFRESH_INTERVAL);
};

// 初始化
onMounted(async () => {
  // 获取服务器时间并启动计时器
  await getTimeNow();
  startTimer();
  // 启动自动刷新
  startAutoRefresh();
});
</script>
<template>
  <div id="index" ref="appRef" class="h-screen flex flex-col">
    <div class="flex-1 flex flex-col">
      <!-- 第一行 -->
      <div class="flex flex-row">
        <dv-decoration-10 class="dv-dec-10" />
        <dv-decoration-8 class="dv-dec-8" :color="decorationColors" />
        <div class="title">
          <span class="title-text">{{ title }}</span>
          <dv-decoration-6
            class="dv-dec-6"
            :reverse="true"
            :color="['#50e3c2', '#67a1e5']"
          />
        </div>
        <dv-decoration-8
          class="dv-dec-8"
          :reverse="true"
          :color="decorationColors"
        />
        <dv-decoration-10 class="dv-dec-10" />
      </div>
      <!-- 第二行 -->
      <div class="flex justify-end">
        <span class="text">
          {{ currentTime }}
        </span>
      </div>
      <!-- 第三行 -->
      <div class="body-box flex-1">
        <div class="content-box flex flex-row items-start space-x-4">
          <div class="w-3/5 h-full">
            <dv-scroll-board class="h-full" :config="config" />
          </div>
          <div class="w-2/5 flex flex-col space-y-4 h-full">
            <!-- 数据块 -->
            <div class="flex flex-row space-x-12 h-[20%]">
              <!-- 今日未发货 -->
              <div class="bg-color-black flex-1">
                <p class="colorBlue fw-b text-center pt-4">今日已发货</p>
                <dv-digital-flop class="dv-dig-flop pl-3" :config="config1" />
              </div>
              <!-- 今日已发货 -->
              <div class="bg-color-black flex-1">
                <p class="colorBlue fw-b text-center pt-4">今日应发货</p>
                <dv-digital-flop class="dv-dig-flop pl-3" :config="config2" />
              </div>
            </div>
            <!-- 饼图 -->
            <div class="bg-color-black h-[40%]">
              <EChartsComponent
                :extraOptions="option"
                type="pie"
                class="w-full h-full"
              />
            </div>
            <!-- 柱状图 -->
            <div class="bg-color-black h-[40%]">
              <EChartsComponent
                :extraOptions="option2"
                type="bar"
                class="w-full h-full"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
// 基础样式
html,
body {
  height: 100%;
}

// 主容器样式
#index {
  background-image: url("../pageBg.png");
  background-size: cover;
  width: 100%;
  height: 100%;
  position: absolute;
  padding: 16px 16px 0 16px;
  color: #d3d6dd;
}

// 装饰元素样式
.dv-dec-10,
.dv-dec-10-s {
  width: 33.3%;
  height: 5px;
}

.dv-dec-8 {
  width: 200px;
  height: 50px;
}

// 标题样式
.title {
  position: relative;
  width: 500px;
  text-align: center;
  background-size: cover;
  background-repeat: no-repeat;

  .title-text {
    font-size: 24px;
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translate(-50%);
  }

  .dv-dec-6 {
    position: absolute;
    bottom: -30px;
    left: 50%;
    width: 250px;
    height: 8px;
    transform: translate(-50%);
  }
}

// 布局相关样式
.aside-width {
  width: 40%;
}

.body-box {
  margin-top: 16px;
}

.content-box {
  height: calc(100% - 60px);
}

// 平行四边形组件样式
.react-base {
  font-size: 18px;
  width: 300px;
  line-height: 50px;
  text-align: center;

  .text {
    display: inline-block;
  }

  &.react-l-s {
    width: 500px;
  }
}

.react-right {
  @extend .react-base;
  transform: skewX(-45deg);

  &.react-l-s {
    text-align: right;
  }

  .react-after {
    position: absolute;
    right: -25px;
    top: 0;
    height: 50px;
    width: 50px;
    background-color: #0f1325;
    transform: skewX(45deg);
  }

  .text {
    transform: skewX(45deg);
  }
}

.react-left {
  @extend .react-base;
  transform: skewX(45deg);
  background-color: #0f1325;
  height: 50px;

  &.react-l-s {
    text-align: left;
  }

  .react-before {
    position: absolute;
    left: -25px;
    top: 0;
    height: 50px;
    width: 50px;
    background-color: #0f1325;
    transform: skewX(-45deg);
  }

  .text {
    transform: skewX(-45deg);
  }
}

// 颜色和背景样式
.bg-color-black {
  background-color: rgba(19, 25, 47, 0.6);
}

.colorBlue {
  color: #257dff !important;

  &:hover {
    color: #257dff !important;
  }
}

// 工具类
.fw-b {
  font-weight: bold;
}
</style>
